/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ventas;

import Clientes.guiPrincipalClientes;
import Creditos.CCredito;
import Utilidades.SpinnerEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;

/**
 *
 * @author alrojas
 */
public class IDetalle extends JFrame{
    
    private Vector <Integer> productos;
    
    private JLabel      clienteLab;
    private JTextField  clienteCam;
    private JTextField  cliente2Cam;
    private JTable      listaTab;
    private DefaultTableModel modeloTab;
    private TableRowSorter<TableModel> clasificador;
    
    private JLabel      totalLab;
    private JTextField  totalCam;
    
    private JLabel tipoDocLab;
    
    private JLabel valeLab;
    private JTextField valeCam; 
    
    private JTextField nroDocumentoTex;
    
    //private JButton     creditoBut;
    private JButton     descartarBut;

    public IDetalle(int venta){
        this.setLayout(new GridBagLayout());
        this.setTitle("Detalle");
        
        inicializarComponentes(venta);
        inicializarListeners();
        
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    
    public void inicializarComponentes(int venta){
        
        productos = new Vector<Integer>();
        
        GridBagConstraints limites = new GridBagConstraints();
        limites.insets = new Insets(2, 2, 2, 2);
        
        limites.fill = GridBagConstraints.HORIZONTAL;
        
        Vector < String > info = null;
        try {
            info = CVenta.dameInfo(venta);
        } catch (SQLException ex) {
            Logger.getLogger(Creditos.IDetalle.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Creditos.IDetalle.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        JPanel tipoDoc = new JPanel();
        tipoDocLab = new JLabel();
        nroDocumentoTex = new JTextField(info.elementAt(3),8);
        if(info.elementAt(2) == "1") tipoDocLab.setText("Boleta de Venta Nro: ");
        else if (info.elementAt(2)=="2") tipoDocLab.setText("Nota de Pedido Nro: ");
        else tipoDocLab.setText("Factura Nro: ");
        tipoDoc.add(tipoDocLab);
        tipoDoc.add(nroDocumentoTex); nroDocumentoTex.setEditable(false);
        limites.gridx = 0; limites.gridy = 0;
        add(tipoDoc,limites);
        
        JPanel panelCliente = new JPanel(new FlowLayout());
        clienteLab = new JLabel("Cliente: "); 
        clienteCam = new JTextField(info.elementAt(0),10); clienteLab.setLabelFor(clienteCam); clienteCam.setHorizontalAlignment(JLabel.CENTER); clienteCam.setEditable(false);
        cliente2Cam = new JTextField(info.elementAt(1),42); clienteLab.setLabelFor(clienteCam); cliente2Cam.setHorizontalAlignment(JLabel.CENTER); cliente2Cam.setEditable(false);
        panelCliente.add(clienteLab); panelCliente.add(clienteCam); panelCliente.add(cliente2Cam);
        limites.gridx = 0; limites.gridy = 1;
        add(panelCliente,limites);
                
        limites.fill = GridBagConstraints.BOTH;
        
        DefaultTableCellRenderer rendererCentro = new DefaultTableCellRenderer();
        rendererCentro.setHorizontalAlignment(JLabel.CENTER);
        
        DefaultTableCellRenderer rendererDerecho = new DefaultTableCellRenderer();
        rendererDerecho.setHorizontalAlignment(JLabel.RIGHT);

        Vector < String > columnNames = new Vector<String>(); columnNames.add("Código"); columnNames.add("Descripción"); columnNames.add("Cantidad"); columnNames.add("P. Unitario (S/.)");  columnNames.add("P. Total (S/.)");     
        Vector productos = null;
        
        try {
            productos = CVenta.dameProductos(venta);
        } catch (SQLException ex) {
            Logger.getLogger(Creditos.IDetalle.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Creditos.IDetalle.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        modeloTab = new DefaultTableModel(productos,columnNames){


                @Override
                public boolean isCellEditable (int row, int column)
                {
                    return false;
                }

            @Override
            public void setValueAt(Object aValue, int row, int column) {
                
                DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
                simbolos.setDecimalSeparator('.');
                DecimalFormat df = new DecimalFormat("#0.00",simbolos);
                if(column == 3){      
                    if(Integer.valueOf(aValue.toString()) <= Integer.valueOf(super.getValueAt(row,2).toString())){
                        float precioUnitario = Float.valueOf(super.getValueAt(row,4).toString());
                        float cantidad = Integer.valueOf(aValue.toString());
                        float precioTotal = precioUnitario * cantidad;

                        super.setValueAt(aValue,row,column);
                        super.setValueAt(df.format(precioTotal),row,5);
                        totalCam.setText(df.format(calcularMontoTotal()));
                    }
                    else{
                        JOptionPane.showMessageDialog(null,"Solo dispone de " + super.getValueAt(row,2).toString() + " existencias!","Aviso",JOptionPane.WARNING_MESSAGE);
                    }
                }
                else{
                    super.setValueAt(aValue,row,column);
                }
            }
                   
            };

        this.clasificador = new TableRowSorter<TableModel>(modeloTab);
        listaTab = new JTable(modeloTab); listaTab.setRowHeight(20); listaTab.setRowSorter(clasificador); listaTab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ((DefaultTableCellRenderer)listaTab.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
        listaTab.getColumnModel().getColumn(0).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(2).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(3).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(4).setCellRenderer(rendererDerecho);       
        
        limites.gridx = 0; limites.gridy = 3; limites.gridwidth = 3;
        JScrollPane barras = new JScrollPane(listaTab); barras.setPreferredSize(new Dimension(490, 150));
        add(barras,limites);
        
        limites.anchor = GridBagConstraints.WEST;
        limites.fill = GridBagConstraints.CENTER;

        JPanel panelVale = new JPanel(new FlowLayout());
        valeLab = new JLabel("Vale Gloria/Laive Nro: ");
        valeLab.setEnabled(false);
        if(info.elementAt(5) != "null"){
            valeLab.setEnabled(true);
            valeCam = new JTextField(info.elementAt(5),10); valeCam.setEnabled(false);
        }
        panelVale.add(valeLab); panelVale.add(valeCam);
        limites.gridy = 4; 
        add(panelVale,limites);
        
        limites.anchor = GridBagConstraints.EAST;
        
        JPanel panelMontoTotal = new JPanel(new FlowLayout());
        totalLab = new JLabel("M. Total (S/.)");
        totalCam = new JTextField(info.elementAt(4),7); totalCam.setHorizontalAlignment(JTextField.RIGHT);
        limites.gridy = 4; //limites.gridwidth = 3;
        panelMontoTotal.add(totalLab); panelMontoTotal.add(totalCam);
        add(panelMontoTotal,limites);
        
        limites.anchor = GridBagConstraints.CENTER;
        
        JPanel panelBotones = new JPanel(new FlowLayout());
        /*
        creditoBut = new JButton("Crédito", new ImageIcon("figuras/credit32.png"));
        creditoBut.setHorizontalTextPosition(SwingConstants.CENTER);
        creditoBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        creditoBut.setVerticalAlignment(SwingConstants.CENTER);*/
        descartarBut = new JButton("Descartar", new ImageIcon("figuras/trash32.png"));
        descartarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        descartarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        descartarBut.setVerticalAlignment(SwingConstants.CENTER);
        limites.gridy = 5; limites.gridwidth = 3;
        /*panelBotones.add(creditoBut);*/ panelBotones.add(descartarBut);
        add(panelBotones,limites);
    }
    
    public void inicializarListeners(){
        
        /*creditoBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(cliente2Cam.getText().compareTo("") != 0 && clienteCam.getText().compareTo("") != 0){
                    if(listaTab.getRowCount() > 0){
                        new Creditos.IAgregar(IDetalle.this);
                    }
                    else{
                        JOptionPane.showMessageDialog(null,"No hay monto que fraccionar!","Aviso",JOptionPane.WARNING_MESSAGE); 
                    }
                                    
                }
                else{
                    JOptionPane.showMessageDialog(null,"No se ha seleccionado al cliente!","Aviso",JOptionPane.WARNING_MESSAGE); 
                }
            }
        });*/
        
        descartarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        
    }
        
    public void actualizarCliente(String codigo, String nombre){
        clienteCam.setText(codigo);
        cliente2Cam.setText(nombre);
    }
    
    public boolean yaEstaAgregado(int codigo){
        return productos.contains(codigo);
    }
    
    public String getCodigoCliente(){
        return clienteCam.getText();
    }
    
    public String getNombreCliente(){
        return cliente2Cam.getText();
    }
    
    public String getMontoCompra(){
        return totalCam.getText();
    }
    
    private float calcularMontoTotal(){
        float suma = 0;
        for(int i = 0; i < listaTab.getRowCount(); i++){
            suma += Float.valueOf(listaTab.getValueAt(i,5).toString());
            
        }
        return suma;
    }
    
    
    public static void main(String args[]){
        
        new IDetalle(1);
    }
    
}
